package com.wzq.upms.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.wzq.permission.client.model.admin.MenuModel;
import com.wzq.permission.client.model.admin.UserModel;
import com.wzq.permission.client.service.ApplicationService;
import com.wzq.permission.client.service.MenuService;
import com.wzq.permission.client.service.UserService;
import com.wzq.upms.annotation.Auth;
import com.wzq.upms.common.utils.MD5Utils;
import com.wzq.upms.core.SessionUtils;

@Controller
public class LoginController {
	@Autowired
	private UserService userServiceClient;
	@Autowired
	private ApplicationService applicationServiceClient;
	@Autowired
	private MenuService menuServiceClient;
	@Value("${app.key}")
	private String appKey;
	
	@RequestMapping("/loginPage")
	@Auth(verifyLogin=false,verifyURL=false)
	public String loginPage(UserModel userModel,HttpServletRequest request){
		return "login";
	}
	
	@RequestMapping("/login")
	@Auth(verifyLogin=false,verifyURL=false)
	public String login(UserModel userModel,String kaptcha,HttpServletRequest request){
		if(StringUtils.isEmpty(kaptcha)){
			request.setAttribute("error","验证码不能为空");
			return "login";
		}else{
			if(!kaptcha.equals(SessionUtils.getKaptcha(request))){
				request.setAttribute("error","验证码错误");
				return "login";
			}
		}
		userModel.setPassword(MD5Utils.encodePwd(userModel.getPassword()));
		UserModel user = userServiceClient.login(userModel,appKey);
		if(user!=null){
			user.setLastLoginTime(new Date());
			userServiceClient.updateBySelective(user);
			SessionUtils.setUser(request, user);
			Long applicationId =applicationServiceClient.getApplicationIdByKey(appKey);
			//设置用户菜单到session
			List<MenuModel> menuList = menuServiceClient.queryMenusByUserId(user.getUserId(), applicationId);
			SessionUtils.setUserMenuList(request, menuList);
			//设置用户权限到session
			List<MenuModel> permissionList =menuServiceClient.queryPermissionByUserId(user.getUserId(), applicationId);
			SessionUtils.setUserPermissionList(request, permissionList);
			return "redirect:/";
		}else{
			request.setAttribute("error","用户或密码错误");
			return "login";
		}
	}
	
	@RequestMapping("/logout")
	@Auth(verifyLogin=false,verifyURL=false)
	public String logout(HttpServletRequest request){
		SessionUtils.removeSession(request);
		return "login";
	}
}
